package com.kit;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 *
 * 
 * @author Yuanqy
 */
public class AESUtil {

	static String MODEL = "AES/CFB/NoPadding";
	static String ivs = "1234567890123456"; // 偏移量
	static String key = "1234567890123456"; // aes 密钥key ：must be 16

	// static String data = "1234567890123456";// 待加密数据
	static String data = "850da68033781fb2640b340a8e";// 待加密数据

	public static void main(String[] args) throws Exception {
		byte[] pwd = encrypt(data.getBytes());
		System.out.println("密文长度[" + pwd.length + "]\t" + byte2hex(pwd));
		byte[] res = decrypt("850da68033781fb2640b340a8e".getBytes());
		System.out.println("解密明文[" + res.length + "]\t" + byte2hex(res) + "\n" + new String(res));
	}

	public static byte[] encrypt(byte[] src) {
		try {
			byte[] raw = key.getBytes();
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance(MODEL);
			IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			return cipher.doFinal(src);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] decrypt(byte[] pwd) {
		try {
			byte[] raw = key.getBytes();
			SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
			Cipher cipher = Cipher.getInstance(MODEL);
			IvParameterSpec iv = new IvParameterSpec(ivs.getBytes());
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			return cipher.doFinal(pwd);
		} catch (Exception e) {
			return null;
		}
	}

	private static String byte2hex(byte[] b) {
		String hs = "";
		String stmp = "";
		String padding = " ";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs = hs + padding + "0" + stmp;
			else
				hs = hs + padding + stmp;
		}
		return hs.toUpperCase();
	}

}